package com.learning.mediacomponent;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.learning.mediacomponent.service.RecordingService;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class RecordActivity extends AppCompatActivity implements View.OnClickListener {

    private boolean isRecording = false; // 记录是否正在录音
    private boolean isPaused = false; // 记录是否暂停录音
    private boolean isPlaying = false; // 记录是否暂停播放
    private long startTime = 0; // 记录录音开始的时间
    private long pauseTime = 0; // 记录录音暂停的时间
    private long resumeTime = 0; // 记录录音继续的时间
    private long noTime = 0; // 记录录音暂停的持续的时间
    private Handler handler = new Handler(); // 用于更新录音时长
    private TextView recordingTimeTextView; // 录音时长文本
    private Button startButton, pauseButton, saveRecordingButton, cancelRecordingButton; // 按钮
    private Runnable updateRecordingTimeRunnable; // 用于更新录音时长的Runnable
    public static List<String> uri_list = new ArrayList<>();

    private AudioManager audioManager;
    private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_record);
        startButton = findViewById(R.id.btn_start_recording); //开始
        saveRecordingButton = findViewById(R.id.btn_save_recording); // 保存
        cancelRecordingButton = findViewById(R.id.btn_cancel_recording); //取消
        pauseButton = findViewById(R.id.btn_pause_recording); //暂停
        recordingTimeTextView = findViewById(R.id.recording_time_text_view);

        pauseButton.setEnabled(false);
        saveRecordingButton.setEnabled(false);
        cancelRecordingButton.setEnabled(false);

        startButton.setOnClickListener(this);
        saveRecordingButton.setOnClickListener(this);
        cancelRecordingButton.setOnClickListener(this);
        pauseButton.setOnClickListener(this);
        uri_list.clear();

        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
            @Override
            public void onAudioFocusChange(int focusChange) {
                if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
                        focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                    Log.i("onAudioFocusChange", "onAudioFocusChange: 监听到音频焦点改变");
                    // 暂停录音
                    isPaused = true;
                    pauseTime = System.currentTimeMillis();
                    pauseButton.setText("继续录音");
                    handler.removeCallbacks(updateRecordingTimeRunnable); // 停止更新时长
                    pauseRecording();
                }
            }
        };

        // 请求音频焦点
        audioManager.requestAudioFocus(audioFocusChangeListener,
                AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_start_recording) {
            // 开始录音
            noTime = 0;
            isRecording = true;
            isPaused = false;
            startRecording();
            startTime = System.currentTimeMillis(); // 记录录音开始时间
            updateRecordingTime();

        } else if (v.getId() == R.id.btn_pause_recording) {
            if (isPaused) {
                resumeTime = System.currentTimeMillis();
                noTime += resumeTime - pauseTime;
                isPaused = false;
                pauseButton.setText("暂停录音");
                updateRecordingTime(); // 重新启动时长更新
                resumeRecording(); // 继续录音
            } else {
                isPaused = true;
                pauseTime = System.currentTimeMillis();
                pauseButton.setText("继续录音");
                handler.removeCallbacks(updateRecordingTimeRunnable); // 停止更新时长
                pauseRecording(); // 暂停录音
            }
        } else if (v.getId() == R.id.btn_save_recording) {
            isRecording = false;
            recordingTimeTextView.setText("00:00:00");
            handler.removeCallbacks(updateRecordingTimeRunnable); // 停止更新时长
            showSaveRecordingDialog();
        } else if (v.getId() == R.id.btn_cancel_recording) {
            if (isRecording) {
                isRecording = false;
                isPaused = false;
                pauseButton.setText("暂停录音");
                recordingTimeTextView.setText("00:00:00");
                handler.removeCallbacks(updateRecordingTimeRunnable);
            }// 停止更新时长
            cancelRecording();

        }

    }


    private void startRecording() {
        Intent intent = new Intent(this, RecordingService.class);
        intent.setAction("START");
        intent.putExtra("outputFile", getExternalCacheDir().getAbsolutePath() + "/temp_record_" + System.currentTimeMillis() + ".3gp");
        startService(intent);
        pauseButton.setEnabled(true);
        saveRecordingButton.setEnabled(true);
        cancelRecordingButton.setEnabled(true);

    }

    //
    private void pauseRecording() {
        Log.i("pauseRecording", "pauseRecording: 暂停");
        Intent intent = new Intent(this, RecordingService.class);
        intent.setAction("PAUSE");
        startService(intent);
    }

    //
    private void resumeRecording() {
        Intent intent = new Intent(this, RecordingService.class);
        intent.setAction("RESUME");
        startService(intent);
    }

    //
    private void saveRecording(String fileName) {
        Intent intent = new Intent(this, RecordingService.class);
        intent.setAction("SAVE");
        intent.putExtra("fileName", fileName);
        startService(intent);
        pauseButton.setEnabled(false);
        saveRecordingButton.setEnabled(false);
        cancelRecordingButton.setEnabled(false);
    }

    //
    private void cancelRecording() {
        Intent intent = new Intent(this, RecordingService.class);
        intent.setAction("CANCEL");
        startService(intent);
        pauseButton.setEnabled(false);
        saveRecordingButton.setEnabled(false);
        cancelRecordingButton.setEnabled(false);
    }


    //

    // 更新录音时长的逻辑
    private void updateRecordingTime() {
        updateRecordingTimeRunnable = new Runnable() {
            @Override
            public void run() {
                if (isRecording && !isPaused) {
                    long elapsedTime = System.currentTimeMillis() - startTime - noTime;
//                    int ms = (int) (elapsedTime / 1000);
                    int seconds = (int) (elapsedTime / 1000) % 60;
                    int minutes = (int) (elapsedTime / (1000 * 60)) % 60;
                    int hours = (int) (elapsedTime / (1000 * 60 * 60)) % 24;
                    // 更新录音时长显示
                    recordingTimeTextView.setText(String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds));

                    // 每隔1秒更新一次
                    handler.postDelayed(this, 1000);
                }
            }
        };

        handler.post(updateRecordingTimeRunnable); // 启动更新
    }


    // 弹出保存录音的对话框，要求用户输入文件名
    private void showSaveRecordingDialog() {
        pauseRecording();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("保存录音");

        // 创建一个 LinearLayout 来包裹 EditText，并设置内边距
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(40, 40, 40, 40); // 设置内边距

        // 设置输入框
        final EditText input = new EditText(this);
//        input.setText("请输入录音名称");
        layout.addView(input);
        builder.setView(layout);

        builder.setPositiveButton("确认", (dialog, which) -> {
            String fileName = input.getText().toString().trim();
            if (!fileName.isEmpty()) {
                saveRecording(fileName);
            } else {
                Toast.makeText(this, "文件名不能为空", Toast.LENGTH_SHORT).show();


            }
        });

        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        builder.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateRecordingTime();

    }

    @Override
    protected void onPause() {
        super.onPause();
//        if (isBound) {
//            unbindService(connection);
//            isBound = false;
//        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelRecording();
        if (audioManager != null && audioFocusChangeListener != null) {
            audioManager.abandonAudioFocus(audioFocusChangeListener);
        }
    }


    //
//    // 开始录音，并在底部显示录音时长
//    private void startRecording() {
//        isRecording = true;
//        isPaused = false;
//        // 创建新的录音文件
//        currentFileName = getExternalCacheDir().getAbsolutePath() + "/temp_record_" + System.currentTimeMillis() + ".3gp";
//
//        recorder = new MediaRecorder();
//        recorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 设置音频源为麦克风
//        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); // 设置输出格式
//        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 设置音频编码
//        recorder.setOutputFile(currentFileName);
//
//        try {
//            recorder.prepare();
//            recorder.start(); // 开始录音
//            startTime = System.currentTimeMillis(); // 记录录音开始时间
//            updateRecordingTime(); // 开始更新录音时长
//
////            Toast.makeText(this, "开始录音", Toast.LENGTH_SHORT).show();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//

    //
//    // 暂停录音
//    private void pauseRecording() {
//        if (recorder != null && isRecording) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                recorder.pause(); // 暂停录音
//            }
//            isPaused = true;
//            pauseTime = System.currentTimeMillis();
//            pauseButton.setText("继续录音");
//            handler.removeCallbacks(updateRecordingTimeRunnable); // 停止更新时长
//        }
//    }
//
//    // 继续录音
//    private void resumeRecording() {
//        if (recorder != null && isRecording) {
//            resumeTime = System.currentTimeMillis();
//            noTime += resumeTime - pauseTime;
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                recorder.resume(); // 恢复录音
//            }
//            isPaused = false;
//            pauseButton.setText("暂停录音");
//            updateRecordingTime(); // 重新启动时长更新
//        }
//    }
//

    //
//    // 保存录音到 MediaStore 并指定用户输入的文件名
//    private void saveRecording(String fileName) {
//        // 停止录音
//        if (recorder != null && isRecording) {
//            recorder.stop();
//            recorder.release();
//            recorder = null;
//            isRecording = false;
//            recordingTimeTextView.setText("00:00:00");
//        }
//
//        handler.removeCallbacks(updateRecordingTimeRunnable); // 停止更新时长
//
//        // 使用 MediaStore 进行保存
//        ContentValues values = new ContentValues();
//        values.put(MediaStore.Audio.Media.DISPLAY_NAME, fileName + ".mp3");
//        values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mpeg");
//
//        ContentResolver resolver = getContentResolver();
//        Uri collection;
//
//        // 根据不同的 API 级别选择保存位置
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            values.put(MediaStore.Audio.Media.RELATIVE_PATH, "Music/Recordings/");
//            collection = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
//        } else {
//            collection = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
//        }
//
//        Uri newUri = resolver.insert(collection, values);
//
//        try {
//            if (newUri != null) {
//                // 将临时文件复制到目标位置
//                ParcelFileDescriptor pfd = resolver.openFileDescriptor(newUri, "w");
//                if (pfd != null) {
//                    File tempFile = new File(currentFileName);
//                    try (FileInputStream fis = new FileInputStream(tempFile);
//                         FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor())) {
//                        byte[] buffer = new byte[1024];
//                        int length;
//                        while ((length = fis.read(buffer)) > 0) {
//                            fos.write(buffer, 0, length);
//                        }
//                    }
//                    tempFile.delete(); // 删除临时文件
//                    Toast.makeText(this, "录音已保存", Toast.LENGTH_SHORT).show();
//                }
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    // 取消录音
//    private void cancelRecording() {
//        if (recorder != null && isRecording) {
//            recorder.stop(); // 停止录音
//            recorder.release();
//            recorder = null;
//            isRecording = false;
//            isPaused = false;
//            pauseButton.setText("暂停录音");
//            recordingTimeTextView.setText("00:00:00");
//            handler.removeCallbacks(updateRecordingTimeRunnable); // 停止更新时长
//
//            // 删除临时文件
//            File tempFile = new File(currentFileName);
//            if (tempFile.exists()) {
//                tempFile.delete();
//            }
//
//
//            Toast.makeText(this, "录音已取消", Toast.LENGTH_SHORT).show();
//        }
//    }
//
//

}